package work.utils;

import static java.lang.System.out;
import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPFile;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import it.sauronsoftware.ftp4j.FTPListParseException;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.h819.core.commons.Configurations;
import com.h819.core.commons.MyLangUtils;
import com.h819.core.db.MyDbUtils;
import com.h819.core.file.MyFileUtils;
import com.h819.core.net.ftp.Ftp4jUtils;
import com.h819.core.utils.MyDateUtils;

/**
 * @Title: FWorksUtils.java
 * @Description: TODO(工作用工具类)
 * @author H819
 * @date 2010-5-5
 * @version V1.0
 */

public class WorksUtils {

	private Logger log = Logger.getLogger(WorksUtils.class);
	private QueryRunner runner = new QueryRunner();
	Connection conn = null;

	private String cons = "@";

	PropertiesConfiguration conf = Configurations
			.getInstance("work.properties");

	Ftp4jUtils ftpUtils = new Ftp4jUtils();

	FTPClient client = null;

	/**
	 * 
	 * @param standardCodeList
	 *            包含标准号的文件，txt 格式，标准号逐行排列
	 * @param tableName
	 *            需要查询的表名: st_standard 为下载标准，st_modify 为下载修改单
	 * @param localDirectory
	 *            指定的下载到本地文件夹
	 */
	public void downLoadPDFFilesFromServer(File standardCodeList,
			String tableName, File localDirectory) {

		conn = MyDbUtils.getInstance("work.properties")
				.getOracleConnection235();

		try {
			// 类变量赋值
			client = ftpUtils.getFTPClient(conf.getString("ftp.server.ip"), 21,
					conf.getString("ftp.client.name"),
					conf.getString("ftp.client.password"));

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			log.info("ftp 无法连接");
			return;
		}

		// 存在的文件，可以下载
		TreeSet<String> existFileName = new TreeSet<String>();
		// 不存在文件，不能下载
		TreeSet<String> notExistFileName = new TreeSet<String>();

		try {

			// 换为可以过滤重复元素的集合
			List<String> fileList = FileUtils.readLines(standardCodeList);
			//
			List<String> fileNamesList = new ArrayList<String>();

			// 得到所有的文件名
			for (String stdCode : fileList) {// for 1

				// 去掉空格
				stdCode = MyLangUtils.trim(stdCode);

				String sql = "";

				if (tableName.equals("st_standard"))
					sql = "select standard_code,namecn,text_address from st_standard where standard_code ='"
							+ stdCode + "'";

				if (tableName.equals("st_modify"))
					sql =

					"select standard_code,MODIFY_NUMBER,file_address from st_modify where standard_code ='"
							+ stdCode + "'";

				// out.println("sql : " + sql);

				// 每个标准号只有一条记录返回,ArrayHandler 适配器合适
				Object[] resultList;

				resultList = runner.query(conn, sql, new ArrayHandler());

				String namecn = "";
				String remoteTextAddress = "";

				if (resultList == null) {
					notExistFileName.add("平台中无此标准号：" + stdCode);
					continue;
				}

				if (resultList[1] != null)
					namecn = resultList[1].toString();

				if (resultList[2] != null && !resultList[2].equals("")) {
					remoteTextAddress = resultList[2].toString();
					existFileName.add(resultList[0].toString());

				} else {
					notExistFileName.add("平台中有题录，但无文本字段为空：" + stdCode);
					continue;
				}

				// 建筑及住宅小区智能化工程检测验收规范
				// 第13部分:安全保密技术要求#Work/DB/DB11!~146.13-2002.PDF
				if (!remoteTextAddress.equals(""))
					fileNamesList.add(namecn + "#" + remoteTextAddress);
			}// end for 1

			// 批量下载
			for (String filename : fileNamesList) {// for 2

				String remoteTextAddress2 = StringUtils.substringAfter(
						StringUtils.substringAfter(filename, "#"), "Work");

				String namecn2 = StringUtils.substringBefore(filename, "#");

				// 去掉不能作为文件名的字符
				namecn2 = MyFileUtils.getWindowsLegalFileName(namecn2, " ");

				String baseName = FilenameUtils.getBaseName(remoteTextAddress2)
						+ "_" + namecn2 + ".pdf";

				String localFileNames = localDirectory.getAbsolutePath() + "\\"
						+ baseName;

				MyFileUtils.forceMkdir(localDirectory);

				log.info("down file '" + remoteTextAddress2 + "' to '"
						+ localFileNames + "'");

				if (ftpUtils.existsFile(client, remoteTextAddress2))
					client.download(remoteTextAddress2,
							new File(localFileNames));
				else {
					notExistFileName.add("平台中有题录，文本字段不为空，但文本丢失"
							+ remoteTextAddress2);
				}

			}// end for2// 记录下载情况

			if (!existFileName.isEmpty())
				FileUtils.writeLines(new File(localDirectory.getAbsolutePath()
						+ "//existFileName.txt"), existFileName);
			if (!notExistFileName.isEmpty())
				FileUtils.writeLines(new File(localDirectory.getAbsolutePath()
						+ "//notExistFileName.txt"), notExistFileName);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			ftpUtils.disconnectQuietly(client);
			DbUtils.closeQuietly(conn);

		}
	}

	/**
	 * 按照给定的 where 条件，从平台中下载文件，where 之前的语句不用写。
	 * 
	 * @param sqlWhereConditon
	 *            where 条件
	 * @param tableName
	 *            需要查询的表名: st_standard 为下载标准，st_modify 为下载修改单
	 * @param localDirectory
	 *            指定的下载到本地文件夹
	 */
	public void downLoadPDFFilesFromServer(String sqlWhereConditon,
			String tableName, File localDirectory) {

		conn = MyDbUtils.getInstance("work.properties")
				.getOracleConnection235();

		try {
			client = ftpUtils.getFTPClient(conf.getString("ftp.server.ip"), 21,
					conf.getString("ftp.client.name"),
					conf.getString("ftp.client.password"));
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (FTPIllegalReplyException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (FTPException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return;
		}

		// 存在的文件，可以下载
		TreeSet<String> existFileName = new TreeSet<String>();
		// 不存在文件，不能下载
		TreeSet<String> notExistFileName = new TreeSet<String>();

		try {
			List<String> fileNamesList = new ArrayList<String>();

			// 得到所有的文件名

			String sql = "";

			if (tableName.equals("st_standard"))
				sql =

				"select standard_code,namecn,text_address from st_standard where "
						+ sqlWhereConditon;

			if (tableName.equals("st_modify"))
				sql =

				"select standard_code,MODIFY_NUMBER,file_address from st_modify where "
						+ sqlWhereConditon;

			log.info("sql : " + sql);
			List<Object[]> resultList;
			resultList = runner.query(conn, sql, new ArrayListHandler());

			if (resultList == null) {
				notExistFileName.add("平台中无此满足条件的标准号：" + sqlWhereConditon);
				return;
			}

			for (Object[] m : resultList) {// for 1

				String namecn = "";
				String remoteTextAddress = "";

				if (m[1] != null)
					namecn = m[1].toString();

				if (m[2] != null && !m[2].toString().equals("")) {
					remoteTextAddress = m[2].toString();
					existFileName.add(m[0].toString());
				} else {
					notExistFileName.add("平台中有题录但无文本：" + m[0].toString());
					continue;
				}
				// 找到地址
				if (!remoteTextAddress.equals(""))
					fileNamesList.add(namecn + "#" + remoteTextAddress);
			}// end for1

			// 批量下载
			for (String filename : fileNamesList) {// for 2

				String remoteTextAddress2 = StringUtils.substringAfter(
						StringUtils.substringAfter(filename, "#"), "Work");

				String namecn2 = StringUtils.substringBefore(filename, "#");

				// 去掉不能作为文件名的字符
				namecn2 = MyFileUtils.getWindowsLegalFileName(namecn2, " ");

				String baseName = FilenameUtils.getBaseName(remoteTextAddress2)
						+ "_" + namecn2 + ".pdf";

				String localFileNames = localDirectory.getAbsolutePath() + "\\"
						+ baseName;

				MyFileUtils.forceMkdir(localDirectory);

				log.info("down file '" + remoteTextAddress2 + "' to '"
						+ localFileNames + "'");

				if (ftpUtils.existsFile(client, remoteTextAddress2))
					client.download(remoteTextAddress2,
							new File(localFileNames));
				else {
					notExistFileName.add("平台中有题录，文本字段不为空，但文本丢失"
							+ remoteTextAddress2);
				}

			}// end for2// 记录下载情况

			log.info("finish. ");

			if (!existFileName.isEmpty())
				FileUtils.writeLines(new File(localDirectory.getAbsolutePath()
						+ "//existFileName.txt"), existFileName);
			if (!notExistFileName.isEmpty())
				FileUtils.writeLines(new File(localDirectory.getAbsolutePath()
						+ "//notExistFileName.txt"), notExistFileName);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			ftpUtils.disconnectQuietly(client);
			DbUtils.closeQuietly(conn);
		}
	}

	/**
	 * 检测平台中的标准文本是否存在
	 * 
	 * @param standardCodeList
	 *            包含标准号的集合.
	 * @param localDirectory
	 *            存放结果的本地文件夹
	 */

	public void checkPDFFilesExistOnServer(Set<String> standardCodeList,
			File localDirectory) {

		conn = MyDbUtils.getInstance("work.properties")
				.getOracleConnection235();

		try {
			client = ftpUtils.getFTPClient(conf.getString("ftp.server.ip"), 21,
					conf.getString("ftp.client.name"),
					conf.getString("ftp.client.password"));
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (FTPIllegalReplyException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (FTPException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return;
		}

		// 存在的文件，可以下载
		TreeSet<String> resultSet = new TreeSet<String>();

		try {

			// 得到所有的文件名
			for (String stdCode : standardCodeList) {// for 1

				// 去掉空格
				stdCode = MyLangUtils.trim(stdCode);

				String sql = "select standard_code,namecn,TEXT_ADDRESS from st_standard where standard_code ='"
						+ stdCode + "'";
				// out.println("sql : " + sql);

				// 每个标准号只有一条记录返回,ArrayHandler 适配器适合
				Object[] resultList;
				resultList = runner.query(conn, sql, new ArrayHandler());

				String namecn = "";
				String remoteTextAddress = "";

				if (resultList == null) {

					// 如果是推标，转化为强标再次查找
					if (StringUtils.contains(stdCode, "/")) {

						// 找到第一个非字母的位置，确定最后一位字母的位置，其之前为标准类别，后面为标准代号
						int index = stdCode.indexOf("/");
						String stdCodeOp = StringUtils.overlay(stdCode, null,
								index, index + 2);
						sql = "select standard_code,namecn,TEXT_ADDRESS from st_standard where standard_code ='"
								+ stdCodeOp + "'";
						resultList = runner
								.query(conn, sql, new ArrayHandler());

						if (resultList == null) {
							resultSet.add("平台中无此标准号 : " + stdCode + " ;经过变化,"
									+ stdCodeOp + "也不存在.");
							continue;
						} else {
							resultSet.add("标准号不一致 : " + stdCode + ",但存在 "
									+ stdCodeOp);
						}

					} else {
						// 如果是强标，转换为其他几个类型的标准，再次查找
						String stdCodeOp = StringUtils.replace(stdCode, " ",
								"/T ");
						sql = "select standard_code,namecn,TEXT_ADDRESS from st_standard where standard_code ='"
								+ stdCodeOp + "'";
						resultList = runner
								.query(conn, sql, new ArrayHandler());

						if (resultList == null) {

							// 如果是强标，转换为其他几个类型的标准，再次查找
							stdCodeOp = StringUtils
									.replace(stdCode, " ", "/Z ");
							sql = "select standard_code,namecn,TEXT_ADDRESS from st_standard where standard_code ='"
									+ stdCodeOp + "'";
							resultList = runner.query(conn, sql,
									new ArrayHandler());

							if (resultList == null) {

								resultSet.add("平台中无此标准号 : " + stdCode
										+ " ;经过变化添加 (/T 或 /Z), 也不存在.");
								continue;

							} else {
								resultSet.add("标准号不一致 : " + stdCode + ",但存在 "
										+ stdCodeOp);
							}

							continue;

						} else {
							resultSet.add("标准号不一致 : " + stdCode + ",但存在 "
									+ stdCodeOp);
						}

					}
				}

				// 中文名称
				if (resultList[1] != null)
					namecn = resultList[1].toString();

				// 地址
				if (resultList[2] == null) {
					resultSet.add("TEXT_ADDRESS is null : " + stdCode);
					continue;
				}

				remoteTextAddress = resultList[2].toString();

				if (remoteTextAddress.equals("")) {
					resultSet.add("TEXT_ADDRESS is null : " + stdCode);
					continue;
				}

				// 为了适应 ftp 帐号的根目录，处理一下
				out.println("remoteTextAddress=" + remoteTextAddress);

				if (StringUtils.contains(remoteTextAddress, "Work"))
					remoteTextAddress = StringUtils.substringAfter(
							remoteTextAddress, "Work");

				else {

					resultSet.add("TEXT_ADDRESS is not null,但格式不合法 : "
							+ remoteTextAddress);
					continue;
				}

				if (!ftpUtils.existsFile(client, remoteTextAddress)) {

					resultSet
							.add("TEXT_ADDRESS is not null,但文本缺失 : " + stdCode);

				}

				out.println(stdCode + " 检查完成，" + remoteTextAddress + " 存在。");

			}// end for 1

			// 记录下载情况

			if (!resultSet.isEmpty())
				FileUtils.writeLines(new File(localDirectory.getAbsolutePath()
						+ "//checkFileResult.txt"), resultSet);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			out.println("检查完成!");
			ftpUtils.disconnectQuietly(client);
			DbUtils.closeQuietly(conn);
		}
	}

	/**
	 * 检查 sqlStr 语句查询结果中的 text_address 文件，在服务器上是否存在。即题录中有，但服务器上面没有的文件。
	 * 
	 * @param sqlStr
	 *            查询语句
	 * @param notExistList
	 *            保存不存在文件
	 */
	public void checkPDFFilesExistOnServer(String sqlStr, File notExistList) {

		conn = MyDbUtils.getInstance("work.properties")
				.getOracleConnection235();

		try {
			client = ftpUtils.getFTPClient("129.9.200.236", 21, "read",
					"readpdf");
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (FTPIllegalReplyException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (FTPException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// 保存记录
		Set<String> resutlSet = new TreeSet<String>();
		//
		// String selectSql =
		// "select standard_code,TEXT_ADDRESS from st_standard t where t.lasted_modify_time < to_date('2010-07-01 16:30:00','yyyy-MM-dd hh24:mi:ss')"
		// +
		// " and t.lasted_modify_time > to_date('2010-01-01 16:30:00','yyyy-MM-dd hh24:mi:ss')";
		// out.println(selectSql);

		// log.info(StringUtils.center(" line ", 80, "*"));

		conn = MyDbUtils.getInstance("h819.properties")
				.getOracleConnection235();

		List<Map<String, Object>> searchResult;
		try {
			searchResult = runner.query(conn, sqlStr, new MapListHandler());

			if (searchResult != null)// 如果查不到结果，返回值为 null，故需要判断

				for (Map m : searchResult) {// 循环记录

					String text_address = null;
					String standard_code = "";
					String key = "";

					for (Iterator it = m.entrySet().iterator(); it.hasNext();) {// 单条记录
						Map.Entry entry = (Map.Entry) it.next();
						// System.out.println(entry.getKey() + " = "
						// + entry.getValue());

						if (entry.getValue() == null)
							continue;

						key = entry.getKey().toString();

						if (key.equals("TEXT_ADDRESS")) {

							text_address = entry.getValue().toString();
							text_address = StringUtils.removeStart(
									text_address, "Work");

						}

						if (key.equals("STANDARD_CODE")) {
							standard_code = entry.getValue().toString();
						}
					}

					// 处理单条记录
					if (text_address == null) {
						resutlSet.add("TEXT_ADDRESS is null :" + standard_code);
						continue;
					}

					// out.println("check :" + text_address);

					if (!ftpUtils.existsFile(client, text_address)) {

						// 记录文本缺失的文件地址
						resutlSet.add("TEXT_ADDRESS is not null，但文件缺失  :"
								+ standard_code);
						// out.println(" ****** not exist :" + text_address);
					}
				}

			if (!resutlSet.isEmpty())
				try {
					FileUtils.writeLines(notExistList, resutlSet);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			ftpUtils.disconnectQuietly(client);
			DbUtils.closeQuietly(conn);
		}
	}

	/**
	 * 根据标准号，查询首标网相应字段
	 * 
	 * @param standardCodeList
	 *            标准号集合
	 * @param descFile
	 *            存放结果的本地文件目录，和源文件位置相同
	 * @param prop
	 *            需要查询的字段，对于与数据库字段，用此来拼写 sql 语句
	 */

	public void checkTiLu(Set<String> standardCodeList, File descFile,
			String[] prop) {

		conn = MyDbUtils.getInstance("work.properties")
				.getOracleConnection235();

		// 保存查询结果
		TreeSet<String> resultSet = new TreeSet<String>();

		try {

			// 得到所有的文件名
			for (String stdCode : standardCodeList) {// for 1

				// 记录特殊情况下的备注
				String remark = "";
				String sqlCon = "";

				// 去掉空格
				stdCode = MyLangUtils.trim(stdCode);

				// 组合要查找的字段
				for (String s : prop)
					sqlCon = sqlCon + "," + s;

				sqlCon = StringUtils.removeStart(sqlCon, ",");
				sqlCon = StringUtils.removeEnd(sqlCon, ",");

				// 基本查询语句
				String sqlBase = "select " + sqlCon
						+ " from st_standard where standard_code ='";

				String sql = sqlBase + stdCode + "'";

				out.println("sql : " + sql);

				// 每个标准号只有一条记录返回,所以ArrayHandler 适配器适合
				Object[] resultList;

				resultList = runner.query(conn, sql, new ArrayHandler());

				// out.println(resultList);

				// 查找不到结果
				if (resultList == null) {

					// 如果是推标，转化为强标再次查找
					if (StringUtils.contains(stdCode, "/")) {

						// 找到第一个非字母的位置，确定最后一位字母的位置，其之前为标准类别，后面为标准代号
						int index = stdCode.indexOf("/");
						String stdCodeOp = StringUtils.overlay(stdCode, null,
								index, index + 2);
						sql = sqlBase + stdCodeOp + "'";

						resultList = runner
								.query(conn, sql, new ArrayHandler());

						if (resultList == null) {
							resultSet.add("平台中无此标准号  " + cons + stdCode + cons
									+ " 经过变化" + cons + stdCodeOp + cons
									+ "也不存在.");
							continue;
						} else {
							resultSet.add("标准号不一致  " + cons + stdCode + cons
									+ "不存在,但存在 " + cons + stdCodeOp + cons);
						}

					} else {
						// 如果是强标，转换为其他几个类型的标准，再次查找
						String stdCodeOp = StringUtils.replace(stdCode, " ",
								"/T ");
						sql = sqlBase + stdCodeOp + "'";
						resultList = runner
								.query(conn, sql, new ArrayHandler());

						if (resultList == null) {

							// 如果是强标，转换为其他几个类型的标准，再次查找
							stdCodeOp = StringUtils
									.replace(stdCode, " ", "/Z ");
							sql = sqlBase + stdCodeOp + "'";
							resultList = runner.query(conn, sql,
									new ArrayHandler());

							if (resultList == null) {

								resultSet.add("平台中无此标准号 " + cons + stdCode
										+ cons + "经过变化添加 (/T 或 /Z), 也不存在.");

								continue;

							} else {
								resultSet.add("标准号不一致  " + cons + stdCode
										+ cons + "但存在 " + cons + stdCodeOp
										+ cons);
							}

							continue;

						} else {
							resultSet.add("标准号不一致 : " + cons + stdCode + cons
									+ ",但存在 " + cons + stdCodeOp + cons);

						}

					}
				}

				String temp = "";

				// 组合结果
				for (int i = 0; i < prop.length; i++) {

					if (resultList[i] != null)
						temp = temp + cons + resultList[i].toString();

				}

				resultSet.add(temp + cons + remark);

			}// end for 1

			// 记录下载情况

			if (!resultSet.isEmpty())
				FileUtils.writeLines(descFile, resultSet);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			out.println("检查完成!");
			DbUtils.closeQuietly(conn);
		}
	}

	/**
	 * 供外部调用的重命名函数
	 * 
	 * @param hostIp
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 */

	public void renameFtpFile(String hostIp, int port, String username,
			String password, String remotePath) {

		try {

			// 因为涉及递归操作，故把ftp服务器连接放入类变量。
			this.getFTPClient(hostIp, port, username, password);

			this.renameFtpFileTemp(remotePath);

		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FTPIllegalReplyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FTPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		ftpUtils.disconnectQuietly(client);

	}

	/**
	 * 获取 FTPClient ，放入类变量，保证操作仅连接一次ftp服务器。尤其是在递归操作中，不能把连接服务器
	 * 
	 * 操作放在循环中
	 * 
	 * 
	 * @param hostIp
	 * @param port
	 * @param username
	 * @param password
	 * @throws IllegalStateException
	 * @throws IOException
	 * @throws FTPIllegalReplyException
	 * @throws FTPException
	 */
	private void getFTPClient(String hostIp, int port, String username,
			String password) throws IllegalStateException, IOException,
			FTPIllegalReplyException, FTPException {

		client = ftpUtils.getFTPClient(hostIp, port, username, password);

	}

	/**
	 * 参考 Ftp4jUtils downLoadDirectory() 函数实现
	 * 
	 * @param remotePath
	 */

	private void renameFtpFileTemp(String remotePath) {

		try {

			client.changeDirectory(remotePath);

			log.info("currentDirectory : " + client.currentDirectory());

			// 记录原始 client 当前目录
			String currentDirectory = client.currentDirectory();

			FTPFile[] fileList = client.list();

			for (FTPFile f : fileList) {

				if (f.getType() == FTPFile.TYPE_FILE) {

					client.rename(f.getName(), f.getName().toUpperCase());

					log.info("file name :" + f.getName());

				}

				if (f.getType() == FTPFile.TYPE_DIRECTORY) {
					// 跳过目录中的 ". " 和 ".." (根目录)
					if (f.getName().equals(".") || f.getName().equals(".."))
						continue;

					log.info("directory name :" + f.getName());

					log.info("current directory :" + client.currentDirectory());

					client.rename(f.getName(), f.getName().toUpperCase());

					// 已经变为大写
					String subDirectory = currentDirectory + "/"
							+ f.getName().toUpperCase();

					client.changeDirectory(subDirectory);

					// 递归
					renameFtpFileTemp(subDirectory);

					// client 的根目录还原为父级
					client.changeDirectoryUp();

				}

			}

		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FTPIllegalReplyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FTPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FTPDataTransferException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FTPAbortedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FTPListParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 上传标准文本。
	 * 
	 * 修改题录的文本字段，pdf 文件需要手工上传至 Work/GN2 中
	 * 
	 * @param remotePath
	 */

	private void uploadFtpFile(String localPath) {

		conn = MyDbUtils.getInstance("work.properties")
				.getOracleConnection235();

		String thisMonthString = MyDateUtils.getToday("yyyy.MM");

		int nums = 0;

		File localf = new File(localPath);

		if (!localf.isDirectory()) {

			System.out.println("请把文件放入一个文件夹中");
			return;
		}

		File[] flist = localf.listFiles();

		try {

			for (File f : flist) {

				if (!f.isFile()) {
					System.out.println(f.getAbsolutePath() + " 不是文件，略过");
					continue;
				}

				String fname = FilenameUtils.getBaseName(f.getAbsolutePath());

				fname = fname.replace('!', '/').replace('~', ' ');
				out.println("完成文件  " + f.getName());

				String sql = "update st_standard set text_address ='Work/GN2/"
						+ thisMonthString + "/" + f.getName()
						+ "' where standard_code ='" + fname + "'";

				// out.println(sql);

				int num = runner.update(conn, sql);

				// out.println(num);

				if (num != 0) {

					nums++;

					File thisMonthFile = new File(localf + "/" + thisMonthString);

					if (!thisMonthFile.exists())
						FileUtils.forceMkdir(thisMonthFile);

					File fTemp = new File(thisMonthFile.getAbsoluteFile() + "/"
							+ f.getName());

					if (fTemp.exists())
						fTemp.delete();

					FileUtils.moveFileToDirectory(f, thisMonthFile, false);

				}
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

			DbUtils.closeQuietly(conn);
			out.println("共计完成文件   " + nums + " 个! ");
			out.println("请把文件夹  " + thisMonthString + " 传入 Work/GN2/ 中! ");
		}

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		WorksUtils u = new WorksUtils();

		PropertiesConfiguration conf = Configurations
				.getInstance("work.properties");

		// u.downLoadPDFFilesFromServer(
		// "standard_code like '%2000%' and class_three_code ='DB11'",
		// new File("D:\\ftpFiles\\"
		// + MyDateUtils.getToday(MyDateUtils
		// .getToday("_yyyy-MM-dd"))));
		// System.out.print(getRecurrent(m, n));

		// 重命名ftp文件
		// u.renameFtpFile(conf.getString("ftp.server.ip"), 21,
		// conf.getString("ftp.client.name.canwrite"),
		// conf.getString("ftp.client.password.canwrite"), "IB2/");

		// 上传文件
		//u.uploadFtpFile("D:\\02\\Standard");
	}
}
